import {createRouter, createWebHistory} from "vue-router";
import {useInfoStore} from "@/store/user/user.ts";


const router = createRouter({
    history: createWebHistory(),
    routes: [
        {
            path: '/',
            redirect: '/login'
        },
        {
          path: '/login',
          name: 'Login',
          component: () => import('@/pages/User/Login/index.vue')
        },
        {
            path: '/test',
            name: 'test',
            component: () => import('@/test/test.vue')
        },
        {
            path: '/hotList',
            name: 'hotList',
            component: () => import('@/pages/HotList/index.vue'),
            meta: {
                pathName: 'hotList',
                requiresAuth: true
            }
        },
        {
            path: '/todo',
            name: 'todo',
            component: () => import('@/pages/ToDo/index.vue')
        },
        {
            path: '/toolbox',
            name: 'toolbox',
            component: () => import('@/pages/Toolbox/index.vue')
        },
        {
            path: '/codeGenerate',
            name: 'codeGenerate',
            component: () => import('@/pages/CodeGenerate/index.vue')
        }
    ],

})

router.beforeEach((to, from, next) => {
    const userStore = useInfoStore();
    const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
    if (requiresAuth && !userStore.isLogin) {
        // 记录页面访问来源，这里简单打印一下，实际可根据需求发送给后端等操作
        console.log(`用户从 ${from.path} 跳转到 ${to.path}`);
        // 如果需要认证的路由（通过meta.requiresAuth判断）且用户未登录（userStore.isLoggedIn为false）
        // 则跳转到登录页面
        next('/login');
    } else {
        next();
    }
});


export default router
